let express = require("express");
let path = require("path"); //系统路径模块
let fs = require("fs"); //文件模块
let jwt = require("jsonwebtoken");
let key = "sdfafjkjsdjflkdskjfk";
let md5=require("blueimp-md5");
const router = express.Router();
const log4js  = require("../config/log.js");
let logger=log4js.getLogger("info");
//获取客户端ip地址
var ip=require("../public/getIp.js");

//登录
router.post("/login", async (req, res) => {
	const logObj={
		date:req.body.date,
		user_actions:req.body.user_actions,
		ip4:ip.getClientIp(req)
	}
	logger.info(logObj);
	const dataObj={
		username:req.body.username,
		password:req.body.password
	}
	let file = path.join(__dirname, '../map/user.json');
	//读取json文件
	await fs.readFile(file, 'utf8', function(err, data) {
		let token = jwt.sign({
		  username: dataObj.username
		}, key);
		res.cookie("token", token);
		if (err) {
			logger.info(err);
			return;
		} else {
			if (JSON.parse(data).length > 0) {
				//将数据库传来的数据转化为JSON格式
				var flag=false;
				let obj = JSON.parse(data);
				for(let i = 0; i < obj.length; i++){
					if(dataObj.username == obj[i].username && dataObj.password == md5(obj[i].password)){
						flag=true;
						break;
					}
				}
				if(flag){
					res.send({
						code:200,
						msg:'登录成功',
						token:token,
						user:dataObj.username
					})
				}else{
					res.send({
						code:205,
						msg:"登录失败"
					})
				}
			}
		}
	});
});
module.exports = router;
